package cn.acewill.yxd.yunxundian.adapter;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;

/**
 * Created by xxx on 2018/1/11.
 */

public class EvaApdater extends RecyclerView.Adapter<EvaApdater.ViewHolder>{

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private Context mContext;
    private List<Schedule> scheduleList;
    private OnBtnClickListener btnClickListener;
    private EvaFilter filter;
    private int LOAD_TYPE = 0;

    public EvaApdater(Context context,List<Schedule> scheduleList,OnBtnClickListener clickListener,int Tag){
        this.mContext = context;
        this.scheduleList = scheduleList;
        this.btnClickListener = clickListener;
        LOAD_TYPE = Tag;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.new_evlation_item_view,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Schedule schedule = scheduleList.get(position);
        holder.bigTag(schedule);
        if (LOAD_TYPE == 1){
            holder.taskStatus.setVisibility(View.GONE);
            holder.sendMail.setVisibility(View.GONE);
        }else{
            holder.taskOA.setVisibility(View.GONE);
        }
        if (schedule.getTitle()!=null){
            holder.taskType.setText(schedule.getTitle());
        }else{
            holder.taskType.setText("未命名");
        }
        if(schedule.getShopID()==0){
            holder.shopName.setText("非门店任务");
        }else{
            try {
                Shop shop=db.selector(Shop.class).where("ID","=",schedule.getShopID()).findFirst();
                if (shop!=null){
                    holder.shopName.setText(shop.getShopName());
                }else{
                    holder.shopName.setText("-----");
                }
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
        if(schedule.getSubtitle()!=null&&schedule.getSubtitle().contains(","))
        {
            String[] tempStr = schedule.getSubtitle().split(",");
            // holder.taskOperator.setText(tempStr[2]);
            if (tempStr.length>=2){
               // holder.taskScore.setText(tempStr[1]+"/"+tempStr[0]);
                holder.taskScore.setText(tempStr[0]+"("+tempStr[1]+")");
            }
        }
        // TODO: 2018/3/1 待开发
        holder.shareTask.setVisibility(View.GONE);

        setTimeAndStatus(schedule,holder);
    }

    @Override
    public int getItemCount() {
        return (scheduleList!=null&&scheduleList.size()>0)?scheduleList.size():0;
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView shopName;
        TextView taskStatus;
        TextView taskOA;
        TextView taskScore;
        TextView taskType;
        TextView taskTime;
        TextView doTask;
        TextView shopSign;
        TextView submitData;
        TextView shareTask;
        TextView lookTask;
        TextView taskTimeType;
        LinearLayout overArea;
        LinearLayout ingArea;
        TextView sendMail;
        public ViewHolder(View itemView) {
            super(itemView);
            shopName =  itemView.findViewById(R.id.shopName);
            taskStatus =  itemView.findViewById(R.id.taskStatus);
            taskScore =  itemView.findViewById(R.id.taskScore);
            taskType =  itemView.findViewById(R.id.taskType);
            taskOA = itemView.findViewById(R.id.taskOA);
            taskTime =  itemView.findViewById(R.id.taskTime);
            doTask =  itemView.findViewById(R.id.doTask);
            shopSign =  itemView.findViewById(R.id.shopSign);
            submitData =  itemView.findViewById(R.id.submitData);
            shareTask =  itemView.findViewById(R.id.shareTask);
            lookTask =  itemView.findViewById(R.id.lookTask);
            taskTimeType =  itemView.findViewById(R.id.taskTimeType);
            overArea =  itemView.findViewById(R.id.overArea);
            ingArea =  itemView.findViewById(R.id.ingArea);
            sendMail= itemView.findViewById(R.id.sendMail);
            sendMail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnClickListener.sendListener((Schedule) sendMail.getTag());
                }
            });
            doTask.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnClickListener.dotaskListener((Schedule)doTask.getTag());
                }
            });
            shopSign.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnClickListener.signListener((Schedule) shopSign.getTag());
                }
            });
            submitData.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnClickListener.submitListener((Schedule) submitData.getTag());
                }
            });
            shareTask.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnClickListener.shareListener((Schedule) shareTask.getTag());
                }
            });
            lookTask.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnClickListener.lookListener((Schedule) lookTask.getTag());
                }
            });
        }
        public void bigTag(Schedule schedule){
            doTask.setTag(schedule);
            shopSign.setTag(schedule);
            submitData.setTag(schedule);
            shareTask.setTag(schedule);
            lookTask.setTag(schedule);
            sendMail.setTag(schedule);
        }
    }
    public interface OnBtnClickListener{
        void dotaskListener(Schedule schedule);
        void signListener(Schedule schedule);
        void submitListener(Schedule schedule);
        void shareListener(Schedule schedule);
        void lookListener(Schedule schedule);
        void sendListener(Schedule schedule);
    }


    private void setTimeAndStatus(Schedule schedule,ViewHolder holder){
        String nowTime = BaseActivity.getNowDate();
        String startTime = schedule.getSchStartTime();
        if (startTime!=null&& !TextUtils.isEmpty(startTime)){
            startTime=startTime.replace("T"," ");
        }else{
            startTime ="";
        }
        String overTime = schedule.getSchEndTime();
        if (overTime!=null&&!TextUtils.isEmpty(overTime)){
            overTime = overTime.replace("T"," ");
        }else{
            overTime = "";
        }
        int result = compare_date(startTime,nowTime);
        if (schedule.getStates()==1){
            setHidden(true,holder,startTime);
            holder.taskTimeType.setText(R.string.eva_time);
            if (result==1){
                holder.taskStatus.setText(R.string.task_delay);
                holder.taskStatus.setTextColor(ContextCompat.getColor(mContext,R.color.red));
            }else{
                holder.taskStatus.setText(R.string.task_unStart);
                holder.taskStatus.setTextColor(ContextCompat.getColor(mContext,R.color.titleColor));
            }
        }else if (schedule.getStates()==2){
            setHidden(true,holder,startTime);
            holder.taskStatus.setText(R.string.task_underWay);
            holder.taskStatus.setTextColor(ContextCompat.getColor(mContext,R.color.green_status));
        }else if (schedule.getStates()==3){
            setHidden(false,holder,overTime);
            holder.taskStatus.setText(R.string.task_isfollowing);
            holder.taskStatus.setTextColor(ContextCompat.getColor(mContext,R.color.yellow_text));
        }else if (schedule.getStates()==4){
            setHidden(false,holder,overTime);
            holder.taskStatus.setText(R.string.task_conplete);
            holder.taskStatus.setTextColor(ContextCompat.getColor(mContext,R.color.green_text));
        }
    }
    //设置时间与状态
    private void setHidden(boolean isDoing,ViewHolder holder,String time){
        if (isDoing){
            holder.overArea.setVisibility(View.GONE);
            holder.ingArea.setVisibility(View.VISIBLE);
            holder.taskTimeType.setText(R.string.eva_time);
            holder.taskTime.setText(time);
        }else{
            holder.ingArea.setVisibility(View.GONE);
            holder.overArea.setVisibility(View.VISIBLE);
            holder.taskTimeType.setText(R.string.eva_time_submit);
            holder.taskTime.setText(time);
        }
    }

    /*时间的比较*/
    public int compare_date(String DATE1, String DATE2) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.getDefault());
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }


    public Filter getFilter() {
        if (filter==null){
            filter = new EvaFilter(this,scheduleList);
        }
        return filter;
    }

    private class EvaFilter extends Filter{
        private EvaApdater adpater;
        private List<Schedule> dataList;
        private List<Schedule> filterList;

        public EvaFilter(EvaApdater adpater,List<Schedule> dataList){
            this.adpater = adpater;
            this.dataList = dataList;
            this.filterList = new ArrayList<>();
        }
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            filterList = new ArrayList<>();
            FilterResults results = new FilterResults();
            if (constraint!=null&&constraint.length()>0){

                for (Schedule schedule:dataList){  //时间与名称
                    Shop shop= null;
                    try {
                        shop = db.selector(Shop.class).where("ID","=",schedule.getShopID()).findFirst();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    if (shop!=null){

                        if (schedule.getStates()<3){
                            String stime = schedule.getSchStartTime().replaceAll("-", "").replace("T", " ");

                            if (stime != null) {
                                if (stime.contains(constraint)||shop.getShopName().contains(constraint))
                                    filterList.add(schedule);
                            }
                        }else {
                            String etime = schedule.getSchEndTime().replaceAll("-", "").replace("T", " ");
                            if (etime != null) {
                                if (etime.contains(constraint)||shop.getShopName().contains(constraint)||schedule.getTitle().contains(constraint)) {
                                    filterList.add(schedule);
                                }
                            }
                        }
                    }
                }
            }else{
                filterList.addAll(dataList);
            }
            results.values = filterList;
            results.count = filterList.size();
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            List<Schedule> valueList = (List<Schedule>) results.values;
            adpater.scheduleList = valueList;
            adpater.notifyDataSetChanged();
        }
    }


}
